﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CdcSoftware.Pivotal.Applications.Core.Client;
using System.Data;
using CdcSoftware.Pivotal.Applications.Core.Common;
using CdcSoftware.Pivotal.Engine;
using CdcSoftware.Pivotal.Engine.Client.Services.Interfaces;
using Pcm.Retail.Client;
using System.Windows.Forms;
using CdcSoftware.Pivotal.Engine.UI.Forms;
using CdcSoftware.Pivotal.Engine.UI.DataTypes.FormParams;
using CdcSoftware.Pivotal.Engine.Types.ServerTasks;

namespace Pcm.Retail.Client.FormTasks
{
    public partial class RE_Member_Create : FormClientTask
    {
        #region Private Variables
        private System.Windows.Forms.TextBox txtCurrentPassword, txtNewPassword, txtConfirmPassword;
        private System.Windows.Forms.Button btnOk, btnCancel;
        private System.Windows.Forms.Label lblCurrentPassword, lblNewPassword, lblConfirmPassword;
        private Form popupChangePassword = null;
        private Form popupAuthorization = null;
        private bool changePassword = false;
        private Id staffId = null;
        private object authorizedBy = null;
        private bool saveForm, srcTxn2, noAuth = false;
        static object staffNewId = null;
        //DS:02112012 - Set the Batch
        static object batchId = null;
        static object recNum = null;
        static object memOrderId = null;
        #endregion

        /// <summary>
        /// OnFormInitialized method call when a new form is opened.
        /// </summary>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-06-13      DS              Initial version for Retail.                                                
        /// </history>
        public override void OnFormInitialized()
        {
            try
            {
                base.OnFormInitialized();
                ParameterList plist = this.TransitionPointParameter.ParameterList;

                this.FormControl.GetControlByDataName("RE_Membership_ID").Focus();

                //Source Transaction 2 will only be enabled when the Txn 1 does not fulfill the criteria for the qualifying amount.
                ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Membership_Reciept_No_2")).ReadOnly = true;
                ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Membership_Reciept_No_2")).Required = false;

                SharedLoad();
                if (this.RecordId == null)
                {
                    if (Convert.IsDBNull(this.PrimaryDataRow["RE_Create_Staff_Id"]) || Convert.IsDBNull(this.PrimaryDataRow["RE_Store_Id"])
                        || Convert.IsDBNull(this.PrimaryDataRow["RE_Batch_Id"]))
                    {
                        DataTable cashierLogsforCurrentBatch = Globals.GetDataTable("RE_All Cashier Logins for Today for In Progress Batch for Current Store ?",
                            new object[] { }, "Staff_Id", "Store_Id", "Batch_Id");

                        if (cashierLogsforCurrentBatch != null && cashierLogsforCurrentBatch.Rows.Count > 0)
                        {
                            if (Convert.IsDBNull(this.PrimaryDataRow["RE_Create_Staff_Id"]))
                                this.PrimaryDataRow["RE_Create_Staff_Id"] = cashierLogsforCurrentBatch.Rows[0]["Staff_Id"];
                            if (Convert.IsDBNull(this.PrimaryDataRow["RE_Store_Id"]))
                                this.PrimaryDataRow["RE_Store_Id"] = cashierLogsforCurrentBatch.Rows[0]["Store_Id"];
                            if (Convert.IsDBNull(this.PrimaryDataRow["RE_Batch_Id"]))
                                this.PrimaryDataRow["RE_Batch_Id"] = cashierLogsforCurrentBatch.Rows[0]["Batch_Id"];
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// On refresh of th eform this event is fired.
        /// </summary>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-08-18      DS              Initial version for Retail.                                                
        /// </history>
        public override void OnFormReloaded()
        {
            try
            {
                base.OnFormReloaded();
                SharedLoad();
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// Shared by both the methods "OnFormInitialized" and "OnFormReloaded".
        /// </summary>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-05-18      DS              Initial version for Retail.                                                
        /// </history>
        private void SharedLoad()
        {
            try
            {
                if (TypeConvert.ToBoolean((this.PrimaryDataRow["RE_Transition_Card"])))
                {
                    //Make the Source Transactions segment read only. The fields on the segment should be non mandatory.
                    MandateSourceTransactions(false);
                }
                else
                    MandateSourceTransactions(true);

                //Make the fields auto populated by Logged-In staff read-only so that if the values are not there, it won't allow saving of a member.
                ((PivotalForeignKey)this.FormControl.GetControlByDataName("RE_Loyalty_Program_Tier_Id")).Required = true;
                ((PivotalDropDown)this.FormControl.GetControlByDataName("RE_Type")).Required = true;
                ((PivotalDropDown)this.FormControl.GetControlByDataName("RE_Status")).Required = true;
                //TO-DO: DS: Once the Logged in POS staff Id is auto populated this field needs to be read-only and required.
                //((PivotalForeignKey)this.FormControl.GetControlByDataName("RE_Create_Staff_Id")).Required = true;
                ((PivotalForeignKey)this.FormControl.GetControlByDataName("RE_Store_Id")).Required = true;
                //((PivotalForeignKey)this.FormControl.GetControlByDataName("RE_Brand_Id")).Required = true;
                ((PivotalForeignKey)this.FormControl.GetControlByDataName("RE_LOB_Id")).Required = true;

                //Remove the Apply button.
                Globals.RemoveButtonBarButton("Apply");

                if (this.TransitionPointParameter.HasValidParameters() && TypeConvert.ToBoolean(this.TransitionPointParameter.GetUserDefinedParameter(1)))
                {
                    //this came from Order.
                    //Remove the Transition Card Group Box and the Authorized By Staff Group box as there can never be a 2nd txn number coming from a SFA_Order Screen.
                    this.FormControl.GetControlByName("PivotalGroupBox3").Visible = false;
                    this.FormControl.GetControlByName("PivotalGroupBox5").Visible = false;
                    ((PivotalTextBox)this.FormControl.GetControlByName("txtStaffCode")).Required = false;
                    ((PivotalForeignKey)this.FormControl.GetControlByName("REAuthorizedById")).Required = false;
                }
                else
                    this.FormControl.GetControlByName("PivotalGroupBox3").Visible = true;

                //BR: code added
                if (this.TransitionPointParameter.UserDefinedParametersNumber == 5)
                {
                    this.PrimaryDataRow["RE_Create_Staff_Id"] = staffNewId;
                    //DS:02112012 - Set the Batch
                    this.PrimaryDataRow["RE_Batch_Id"] = batchId;
                    this.PrimaryDataRow["RE_Membership_Reciept_No"] = recNum;
                    this.PrimaryDataRow["RE_Membership_Order_Id"] = memOrderId;
                    //Set new member to VIP and Status to pending
                    this.PrimaryDataRow["RE_Type"] = "Member";
                    this.PrimaryDataRow["RE_Status"] = "Pending";

                    //Set other fields
                    DataTable dEmployee = Globals.GetDataTable("Employee id of current user", new object[] { null }, "RE_Loyalty_Program_Tier_Id", "RE_Store_Id",
                        "RE_Brand_Id", "RE_Line_Of_Business_Id");

                    if (dEmployee != null && dEmployee.Rows.Count == 1)
                    {
                        this.PrimaryDataRow["RE_Loyalty_Program_Tier_Id"] = dEmployee.Rows[0]["RE_Loyalty_Program_Tier_Id"];
                        this.PrimaryDataRow["RE_Store_Id"] = dEmployee.Rows[0]["RE_Store_Id"];
                        //this.PrimaryDataRow["RE_Brand_Id"] = dEmployee.Rows[0]["RE_Brand_Id"];
                        this.PrimaryDataRow["RE_LOB_Id"] = dEmployee.Rows[0]["RE_Line_Of_Business_Id"];

                        if (dEmployee.Rows[0]["RE_Loyalty_Program_Tier_Id"] != DBNull.Value)
                        {
                            //Set the Program_Id
                            object programId = Globals.SqlIndex("RE_Loyalty_Program_Tier", "Program_Id", Id.Create(dEmployee.Rows[0]["RE_Loyalty_Program_Tier_Id"]));
                            this.PrimaryDataRow["RE_Loyalty_Program_Id"] = programId;
                        }
                    }
                }
            }
            finally
            {
                staffNewId = null;
                //DS:02112012 - Set the Batch
                batchId = null;
                recNum = null;
                memOrderId = null;
            }

        }

        /// <summary>
        /// Saves the Contact record
        /// </summary>
        /// <returns>Returns true for successful save else false</returns>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-05-18      DS              Initial version for Retail.                                                
        /// </history>
        public override bool SaveRecord()
        {
            bool saveRecord = noAuth = false;
            try
            {
                //DS: 27032013 - Moved formula calculation to code.
                //NN 27 May 2013:Added code to check for NULL values
                //If all the 3 values are NULL then setting the Main field as NULL
                if (TypeConvert.ToString(this.PrimaryDataRow["RE_Mobile_Country_Code"]) != string.Empty ||
                 TypeConvert.ToString(this.PrimaryDataRow["RE_Mobile_Area_Code"]) != string.Empty ||
                 TypeConvert.ToString(this.PrimaryDataRow["RE_Mobile_Number"]) != string.Empty)
                {
                    this.PrimaryDataRow["Mobile"] = '+' + TypeConvert.ToString(this.PrimaryDataRow["RE_Mobile_Country_Code"]) +
                                            TypeConvert.ToString(this.PrimaryDataRow["RE_Mobile_Area_Code"]) + TypeConvert.ToString(this.PrimaryDataRow["RE_Mobile_Number"]);
                }
                else
                    this.PrimaryDataRow["Mobile"] = DBNull.Value;


                if (this.RecordId == null)
                {
                    saveRecord = this.AddRecord();
                }
                else
                {
                    if (ContactDupCheck())
                        return false;

                    //On change of field RE_Status from Pending to Active, Create a new row in the RE_Membership_History table.
                    if (string.Equals(this.PrimaryDataRow["RE_Status"].ToString(), "Active") &&
                        string.Equals(this.PrimaryDataRow["RE_Status", DataRowVersion.Original].ToString(), "Pending"))
                    {
                        //Create a new row in the RE_Membership_History table.
                        DataRow reMembershipHistoryRow = this.DataSet.Tables["RE_Membership_History_Contact_"].NewRow();
                        reMembershipHistoryRow["Contact_Id"] = this.RecordId.ToByteArray();
                        reMembershipHistoryRow["Activity"] = Globals.GetComboChoiceText("RE_Membership_History", "Activity", "Activated");
                        reMembershipHistoryRow["Activity_Description"] = "Membership Activated";
                        reMembershipHistoryRow["Activity_Date"] = DateTime.Now;

                        this.DataSet.Tables["RE_Membership_History_Contact_"].Rows.Add(reMembershipHistoryRow);
                    }

                    //If the Membership ID field is changed from its initial value to a different one, Create a new row in the RE_Membership_History table.
                    if (!string.Equals(this.PrimaryDataRow["RE_Membership_ID"].ToString(), this.PrimaryDataRow["RE_Membership_ID", DataRowVersion.Original].ToString()))
                    {
                        //Create a new row in the RE_Membership_History table.
                        DataRow reMembershipHistoryRow = this.DataSet.Tables["RE_Membership_History_Contact_"].NewRow();
                        reMembershipHistoryRow["Contact_Id"] = this.RecordId.ToByteArray();
                        reMembershipHistoryRow["Activity"] = Globals.GetComboChoiceText("RE_Membership_History", "Activity", "Card Replaced");
                        reMembershipHistoryRow["Activity_Description"] = "Membership ID Changed";
                        reMembershipHistoryRow["Activity_Date"] = DateTime.Now;

                        this.DataSet.Tables["RE_Membership_History_Contact_"].Rows.Add(reMembershipHistoryRow);
                    }

                    //Call the method which shares the same code with AddRecord.
                    if (!SharedSave())
                        return false;                   

                    //If authorization goes through, then save the form with the secondary record in it..
                    if (saveForm)
                    {
                        //If the authorization passes through, then add a new row to the secondary RE_Authorization
                        AddAuthorizationRow();

                        saveRecord = base.SaveRecord();
                        base.LoadRecord();
                    }
                }
                ////Get error with this. Platform Issue.
                //if (saveRecord)
                //{
                //    if(!(this.TransitionPointParameter.HasValidParameters() && TypeConvert.ToBoolean(this.TransitionPointParameter.GetUserDefinedParameter(1))))
                //    {
                //        Id recordId = this.RecordId;
                //        this.FormView.CloseForm(true);
                //        Globals.ShowForm("Contact", recordId, null, ActionTargetWindow.Current);
                //    }
                //}
            }
            catch (Exception exc)
            {
                return Globals.HandleException(exc, true);
            }
            return saveRecord;
        }

        /// <summary>
        /// Show the authorization Pop-up.
        /// </summary>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-05-18      DS              Initial version for Retail.                                                
        /// </history>
        private void ShowChangePasswordPopup()
        {
            changePassword = true;
            popupChangePassword = new Form();

            this.txtCurrentPassword = new System.Windows.Forms.TextBox();
            this.txtNewPassword = new System.Windows.Forms.TextBox();
            this.txtConfirmPassword = new System.Windows.Forms.TextBox();
            this.btnOk = new System.Windows.Forms.Button();
            this.btnCancel = new System.Windows.Forms.Button();
            this.lblCurrentPassword = new System.Windows.Forms.Label();
            this.lblNewPassword = new System.Windows.Forms.Label();
            this.lblConfirmPassword = new System.Windows.Forms.Label();
            popupChangePassword.SuspendLayout();
            // 
            // txtCurrentPassword
            // 
            this.txtCurrentPassword.Location = new System.Drawing.Point(181, 30);
            this.txtCurrentPassword.Name = "txtCurrentPassword";
            this.txtCurrentPassword.Size = new System.Drawing.Size(109, 20);
            this.txtCurrentPassword.TabIndex = 0;
            this.txtCurrentPassword.UseSystemPasswordChar = true;
            // 
            // txtNewPassword
            // 
            this.txtNewPassword.Location = new System.Drawing.Point(181, 71);
            this.txtNewPassword.Name = "txtNewPassword";
            this.txtNewPassword.Size = new System.Drawing.Size(109, 20);
            this.txtNewPassword.TabIndex = 1;
            this.txtNewPassword.UseSystemPasswordChar = true;
            // 
            // txtConfirmPassword
            // 
            this.txtConfirmPassword.Location = new System.Drawing.Point(181, 112);
            this.txtConfirmPassword.Name = "txtNewPassword";
            this.txtConfirmPassword.Size = new System.Drawing.Size(109, 20);
            this.txtConfirmPassword.TabIndex = 2;
            this.txtConfirmPassword.UseSystemPasswordChar = true;
            // 
            // btnOk
            // 
            this.btnOk.Location = new System.Drawing.Point(134, 161);
            this.btnOk.Name = "Ok";
            this.btnOk.Size = new System.Drawing.Size(75, 23);
            this.btnOk.TabIndex = 3;
            this.btnOk.Text = "Ok";
            this.btnOk.BringToFront();
            this.btnOk.UseVisualStyleBackColor = true;
            this.btnOk.Click += new System.EventHandler(this.Ok_Click);
            // 
            // btnCancel
            // 
            this.btnCancel.Location = new System.Drawing.Point(215, 161);
            this.btnCancel.Name = "Cancel";
            this.btnCancel.Size = new System.Drawing.Size(75, 23);
            this.btnCancel.TabIndex = 4;
            this.btnCancel.Text = "Cancel";
            this.btnCancel.UseVisualStyleBackColor = true;
            // 
            // lblCurrentPassword
            // 
            this.lblCurrentPassword.AutoSize = true;
            this.lblCurrentPassword.Location = new System.Drawing.Point(43, 33);
            this.lblCurrentPassword.Name = "lblCurrentPassword";
            this.lblCurrentPassword.Size = new System.Drawing.Size(138, 15);
            this.lblCurrentPassword.TabIndex = 5;
            this.lblCurrentPassword.Text = "Current Password:";
            // 
            // lblNewPassword
            // 
            this.lblNewPassword.AutoSize = true;
            this.lblNewPassword.Location = new System.Drawing.Point(43, 74);
            this.lblNewPassword.Name = "lblNewPassword";
            this.lblNewPassword.Size = new System.Drawing.Size(138, 15);
            this.lblNewPassword.TabIndex = 5;
            this.lblNewPassword.Text = "New Password:";
            // 
            // lblConfirmPassword
            // 
            this.lblConfirmPassword.AutoSize = true;
            this.lblConfirmPassword.Location = new System.Drawing.Point(43, 115);
            this.lblConfirmPassword.Name = "lblConfirmPassword";
            this.lblConfirmPassword.Size = new System.Drawing.Size(138, 15);
            this.lblConfirmPassword.TabIndex = 6;
            this.lblConfirmPassword.Text = "Confirm Password:";
            // 
            // Form1
            // 
            popupChangePassword.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            popupChangePassword.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            popupChangePassword.AcceptButton = this.btnOk;
            popupChangePassword.CancelButton = this.btnCancel;
            popupChangePassword.ClientSize = new System.Drawing.Size(348, 224);
            popupChangePassword.StartPosition = FormStartPosition.CenterScreen;
            popupChangePassword.Controls.Add(this.lblCurrentPassword);
            popupChangePassword.Controls.Add(this.lblNewPassword);
            popupChangePassword.Controls.Add(this.lblConfirmPassword);
            popupChangePassword.Controls.Add(this.btnOk);
            popupChangePassword.Controls.Add(this.btnCancel);
            popupChangePassword.Controls.Add(this.txtCurrentPassword);
            popupChangePassword.Controls.Add(this.txtNewPassword);
            popupChangePassword.Controls.Add(this.txtConfirmPassword);
            popupChangePassword.Name = "popupChangePassword";
            popupChangePassword.Text = "Change Password";
            popupChangePassword.ResumeLayout(false);
            popupChangePassword.PerformLayout();
            popupChangePassword.ShowDialog();
        }

        /// <summary>
        /// Show the authorization Pop-up.
        /// </summary>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-05-18      DS              Initial version for Retail.                                                
        /// </history>
        private void ShowAuthorizationPopup()
        {
            changePassword = false;
            popupAuthorization = new Form();

            this.txtCurrentPassword = new System.Windows.Forms.TextBox();
            this.btnOk = new System.Windows.Forms.Button();
            this.btnCancel = new System.Windows.Forms.Button();
            this.lblCurrentPassword = new System.Windows.Forms.Label();
            popupAuthorization.SuspendLayout();
            // 
            // txtCurrentPassword
            // 
            this.txtCurrentPassword.Location = new System.Drawing.Point(181, 30);
            this.txtCurrentPassword.Name = "txtCurrentPassword";
            this.txtCurrentPassword.Size = new System.Drawing.Size(109, 20);
            this.txtCurrentPassword.TabIndex = 1;
            this.txtCurrentPassword.UseSystemPasswordChar = true;
            // 
            // btnOk
            // 
            this.btnOk.Location = new System.Drawing.Point(134, 80);
            this.btnOk.Name = "Ok";
            this.btnOk.Size = new System.Drawing.Size(75, 23);
            this.btnOk.TabIndex = 2;
            this.btnOk.Text = "Ok";
            this.btnOk.UseVisualStyleBackColor = true;
            this.btnOk.Click += new System.EventHandler(this.Ok_Click);
            // 
            // btnCancel
            // 
            this.btnCancel.Location = new System.Drawing.Point(215, 80);
            this.btnCancel.Name = "Cancel";
            this.btnCancel.Size = new System.Drawing.Size(75, 23);
            this.btnCancel.TabIndex = 3;
            this.btnCancel.Text = "Cancel";
            this.btnCancel.UseVisualStyleBackColor = true;
            // 
            // lblCurrentPassword
            // 
            this.lblCurrentPassword.AutoSize = true;
            this.lblCurrentPassword.Location = new System.Drawing.Point(43, 33);
            this.lblCurrentPassword.Name = "lblCurrentPassword";
            this.lblCurrentPassword.Size = new System.Drawing.Size(138, 15);
            this.lblCurrentPassword.TabIndex = 5;
            this.lblCurrentPassword.Text = "Password:";
            // 
            // Form1
            // 
            popupAuthorization.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            popupAuthorization.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            popupAuthorization.AcceptButton = this.btnOk;
            popupAuthorization.CancelButton = this.btnCancel;
            popupAuthorization.ClientSize = new System.Drawing.Size(348, 133);
            popupAuthorization.StartPosition = FormStartPosition.CenterScreen;
            popupAuthorization.Controls.Add(this.lblCurrentPassword);
            popupAuthorization.Controls.Add(this.btnOk);
            popupAuthorization.Controls.Add(this.btnCancel);
            popupAuthorization.Controls.Add(this.txtCurrentPassword);
            popupAuthorization.Name = "popupAuthorization";
            popupAuthorization.Text = "Enter Password";
            popupAuthorization.ResumeLayout(false);
            popupAuthorization.PerformLayout();
            popupAuthorization.ShowDialog();
        }

        /// <summary>
        /// Saves the Contact record
        /// </summary>
        /// <returns>Returns true for successful save else false</returns>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-05-18      DS              Initial version for Retail.                                                
        /// </history>
        protected bool AddRecord()
        {
            bool addRecord = noAuth = false;
            object obj = this.PrimaryDataRow["RE_Create_Staff_Id"];
            object obj2 = this.PrimaryDataRow["RE_Membership_Reciept_No"];

            try
            {
                //DS: 27032013 - Moved formula calculation to code.
                //NN 27 May 2013:Added code to check for NULL values
                //If all the 3 values are NULL then setting the Main field as NULL
                if (TypeConvert.ToString(this.PrimaryDataRow["RE_Mobile_Country_Code"]) != string.Empty ||
                TypeConvert.ToString(this.PrimaryDataRow["RE_Mobile_Area_Code"]) != string.Empty ||
                TypeConvert.ToString(this.PrimaryDataRow["RE_Mobile_Number"]) != string.Empty)
                {
                    this.PrimaryDataRow["Mobile"] = '+' + TypeConvert.ToString(this.PrimaryDataRow["RE_Mobile_Country_Code"]) +
                                            TypeConvert.ToString(this.PrimaryDataRow["RE_Mobile_Area_Code"]) + TypeConvert.ToString(this.PrimaryDataRow["RE_Mobile_Number"]);
                }
                else
                    this.PrimaryDataRow["Mobile"] = DBNull.Value;


                if (ContactDupCheck())
                    addRecord = false;
                else
                {
                    //Call the method which shares the same code with AddRecord.
                    if (!SharedSave())
                        return false;

                    if (saveForm)
                    {
                        //Save the primary form.
                        addRecord = base.SaveRecord();

                        //If the authorization passes through, then add a new row to the secondary RE_Authorization in case it required one.
                        if(!noAuth)
                            AddAuthorizationRow();

                        //Create a new row in the RE_Membership_History table.
                        DataRow reMembershipHistoryRow = this.DataSet.Tables["RE_Membership_History_Contact_"].NewRow();
                        reMembershipHistoryRow["Contact_Id"] = this.RecordId.ToByteArray();
                        reMembershipHistoryRow["Activity"] = Globals.GetComboChoiceText("RE_Membership_History", "Activity", "Enrolled");
                        reMembershipHistoryRow["Activity_Description"] = "Member created.";
                        reMembershipHistoryRow["Activity_Date"] = DateTime.Now;

                        this.DataSet.Tables["RE_Membership_History_Contact_"].Rows.Add(reMembershipHistoryRow);

                        addRecord = base.SaveRecord();
                        base.LoadRecord();
                    }
                }
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
            return addRecord;
        }

        /// <summary>
        /// Adds a new row to the RE_Authorization secondary, but save will happen post method call.
        /// </summary>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-05-18      DS              Initial version for Retail.                                                
        /// </history>
        private void AddAuthorizationRow()
        {
            //If the authorization passes through, then add a new row to the secondary RE_Authorization
            DataRow reAuthorizationRow = this.DataSet.Tables["RE_Authorization_Contact_Id"].NewRow();
            reAuthorizationRow["Contact_Id"] = TypeConvert.ToDBValue(this.RecordId);
            reAuthorizationRow["RE_Authorized_By_Id"] = authorizedBy;
            reAuthorizationRow["Authorized"] = true;
            if (srcTxn2)
            {
                reAuthorizationRow["Event"] = "Two source transactions are used.";
                reAuthorizationRow["Comments"] = "Two source transactions are used for this member with the Receipt Numbers as: \"" +
                    this.PrimaryDataRow["RE_Membership_Reciept_No"].ToString() + "\" and \"" + this.PrimaryDataRow["RE_Membership_Reciept_No_2"].ToString() + "\".";
            }
            else
            {
                reAuthorizationRow["Event"] = "Transition card is used and authorized.";
                reAuthorizationRow["Comments"] = "Transition card is used for the creation of the member.";
            }

            this.DataSet.Tables["RE_Authorization_Contact_Id"].Rows.Add(reAuthorizationRow);
        }

        /// <summary>
        /// Common code shared by AddRecord and SaveRecord.
        /// </summary>
        /// <returns></returns>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-05-18      DS              Initial version for Retail.                                                
        /// </history>
        private bool SharedSave()
        {
            //Check for the total value of transaction to be greater than the qualifying amount for the program in the currency of the transaction.
            if (!TypeConvert.ToBoolean((this.PrimaryDataRow["RE_Transition_Card"])))
            {
                if (this.PrimaryDataRow["RE_Membership_Order_Id"] != DBNull.Value && this.PrimaryDataRow["RE_Store_Id"] != DBNull.Value)
                {
                    double transactionAmt2 = 0;
                    double transactionAmt1 = TypeConvert.ToDouble(Globals.ServerSqlIndex("SFA_Order", "Quote_Total", Id.Create(this.PrimaryDataRow["RE_Membership_Order_Id"])));

                    if (this.PrimaryDataRow["RE_Membership_2_Order_Id"] != DBNull.Value)
                        transactionAmt2 = TypeConvert.ToDouble(Globals.ServerSqlIndex("SFA_Order", "Quote_Total", Id.Create(this.PrimaryDataRow["RE_Membership_2_Order_Id"])));

                    //Get the currency for the Store.
                    object currency = Globals.ServerSqlIndex("RE_Store", "Currency_Id", Id.Create(this.PrimaryDataRow["RE_Store_Id"]));

                    //Get the Tier Qualifying amount for the Loyalty Program Tier and the currency.
                    DataTable qualifyingAmt = Globals.GetDataTable("RE_Tier_Qualification for Loyalty Program Tier? Currency?", new object[] { this.PrimaryDataRow["RE_Loyalty_Program_Tier_Id"], currency },
                        new string[] { "Qualifying_Amount" });

                    if (qualifyingAmt != null && qualifyingAmt.Rows.Count > 0 && ((transactionAmt1 + transactionAmt2) < TypeConvert.ToDouble(qualifyingAmt.Rows[0]["Qualifying_Amount"])))
                    {
                        PivotalMessageBox.Show("The total value of the transaction(s) should be more than the qualifying amount for the program in the currency of the transaction.",
                            MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return false;
                    }
                    else
                    {
                        if (this.PrimaryDataRow["RE_Membership_2_Order_Id"] != DBNull.Value)
                        {
                            //Here two source transactions are used.
                            //show the authorization screen for the “In-Charge” to key in the password and authorize the transaction. 
                            //If authorization fails, then do not save the form.
                            DataTable staffLogin = Globals.GetDataTable("RE_All Staff Logins for Today with Can Authorize and Store?", new object[] { this.PrimaryDataRow["RE_Store_Id"] },
                                new string[] { "Staff_Id", "Staff_Code", "Out_Time" });

                            //Check in the staff login secondary for the day, if the user is already logged in (row exists for the staff where out time is null) (all records across all stores)
                            int count = staffLogin.AsEnumerable().Count(a => Id.Create(a["Staff_Id"]).ToString() == Id.Create(this.PrimaryDataRow["RE_Authorized_By_Id"]).ToString()
                                && Convert.IsDBNull(a["Out_Time"]));

                            if (count > 0)
                            {
                                //Check if for the selected staff, the Prompt_To_Change field is set to true.
                                if (TypeConvert.ToBoolean(Globals.ServerSqlIndex("RE_Staff", "Prompt_To_Reset", Id.Create(this.PrimaryDataRow["RE_Authorized_By_Id"]))))
                                    ShowChangePasswordPopup();
                                else
                                    ShowAuthorizationPopup();
                            }
                            else
                            {
                                //Show the prompt that the staff is not logged into the store.
                                PivotalMessageBox.Show("Staff is either not logged into the Store or does not have necessary permission to Authorize.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return false;
                            }         
                        }
                        else
                        {
                            //Add the record with the Membership History.
                            noAuth = saveForm = true;
                        }
                    }
                }
            }
            else
            {
                //When the user tries to save the form, if the transition Boolean is checked, 
                //show the authorization screen for the “In-Charge” to key in the password and authorize the transaction.
                //If authorization fails, then do not save the form.
                DataTable staffLogin = Globals.GetDataTable("RE_All Staff Logins for Today with Can Authorize and Store?", new object[] { this.PrimaryDataRow["RE_Store_Id"] },
                                new string[] { "Staff_Id", "Staff_Code", "Out_Time" });

                //Check in the staff login secondary for the day, if the user is already logged in (row exists for the staff where out time is null) (all records across all stores)
                int count = staffLogin.AsEnumerable().Count(a => Id.Create(a["Staff_Id"]).ToString() == Id.Create(this.PrimaryDataRow["RE_Authorized_By_Id"]).ToString()
                    && Convert.IsDBNull(a["Out_Time"]));

                if (count > 0)
                {
                    //Check if for the selected staff, the Prompt_To_Change field is set to true.
                    if (TypeConvert.ToBoolean(Globals.ServerSqlIndex("RE_Staff", "Prompt_To_Reset", Id.Create(this.PrimaryDataRow["RE_Authorized_By_Id"]))))
                        ShowChangePasswordPopup();
                    else
                        ShowAuthorizationPopup();
                }
                else
                {
                    //Show the prompt that the staff is not logged into the store.
                    PivotalMessageBox.Show("Staff is either not logged into the Store or does not have necessary permission to Authorize.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }  
            }
            return true;
        }

        /// <summary>
        /// Check for duplicate Contacts. If found, then show the list and let the user modify the contact. Do not allow the user to create a duplicate Contact.
        /// </summary>
        /// <returns></returns>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-05-18      DS              Initial version for Retail.                                                
        /// </history>
        private bool ContactDupCheck()
        {
            bool dupFound = false;
            try
            {
                DataTable contactsForBrandAndIDNum = Globals.GetDataTable("RE_Members with with Brand Id? NRIC/FIN/Passport No.? Contact Id Not?",
                    new object[] { this.PrimaryDataRow["RE_Brand_Id"], this.PrimaryDataRow["RE_Identification_Number"], 
                    (this.RecordId==null)?null:TypeConvert.ToDBValue(this.RecordId) }, new string[] { "Contact_Id" });

                if (contactsForBrandAndIDNum != null && contactsForBrandAndIDNum.Rows.Count > 0)
                {
                    ShowListAndEdit(contactsForBrandAndIDNum, "NRIC/FIN/Passport No.");
                    dupFound = true;
                }
                else
                {
                    DataTable contactsForMembership = Globals.GetDataTable("RE_Members with with Brand Id? Membership ID? Contact Id Not?",
                            new object[] { this.PrimaryDataRow["RE_Brand_Id"], this.PrimaryDataRow["RE_Membership_ID"],  
                                (this.RecordId==null)?null:TypeConvert.ToDBValue(this.RecordId)}, new string[] { "Contact_Id" });

                    if (contactsForMembership != null && contactsForMembership.Rows.Count > 0)
                    {
                        ShowListAndEdit(contactsForMembership, "Membership ID.");
                        dupFound = true;
                    }
                    else
                    {
                        DataTable contactsForBrandAndEmail = Globals.GetDataTable("RE_Members with with Brand Id? Email? Contact Id Not?",
                            new object[] { this.PrimaryDataRow["RE_Brand_Id"], this.PrimaryDataRow["Email"], 
                        (this.RecordId==null)?null:TypeConvert.ToDBValue(this.RecordId) }, new string[] { "Contact_Id" });

                        if (contactsForBrandAndEmail != null && contactsForBrandAndEmail.Rows.Count > 0)
                        {
                            ShowListAndEdit(contactsForBrandAndEmail, "Email.");
                            dupFound = true;
                        }
                        else
                        {
                            DataTable contactsForBrandAndMobile = Globals.GetDataTable("RE_Members with with Brand Id? Mobile? Contact Id Not?",
                                new object[] { this.PrimaryDataRow["RE_Brand_Id"], this.PrimaryDataRow["Mobile"], 
                            (this.RecordId==null)?null:this.RecordId.ToByteArray() }, new string[] { "Contact_Id" });

                            if (contactsForBrandAndMobile != null && contactsForBrandAndMobile.Rows.Count > 0)
                            {
                                ShowListAndEdit(contactsForBrandAndMobile, "Mobile.");
                                dupFound = true;
                            }
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                return Globals.HandleException(exc, true);
            }
            return dupFound;
        }

        /// <summary>
        /// Show the user duplicate contacts and allow him to modify.
        /// </summary>
        /// <param name="contacts">Duplicate Contacts</param>
        /// <param name="dupField">Duplicate Field</param>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-05-18      DS              Initial version for Retail.                                                
        /// </history>
        private void ShowListAndEdit(DataTable contacts, string dupField)
        {
            PivotalMessageBox.Show("Duplicate Contacts found for the Field: " + dupField + Environment.NewLine + "Please examine the duplicates and Modify.",
                MessageBoxButtons.OK, MessageBoxIcon.Warning);

            //Showing all duplicate records for user selection
            Id selectedDuplicateContactId = Globals.ShowSingleSelectionList(contacts, "Duplicate Contacts", string.Empty);
            if (selectedDuplicateContactId != null)
            {
                if (this.TransitionPointParameter.HasValidParameters() && TypeConvert.ToBoolean(this.TransitionPointParameter.GetUserDefinedParameter(1)))
                {
                    DataTable contact = Globals.GetDataTable("RE_Contacts with Contact id ?", new object[] { selectedDuplicateContactId }, "RE_Type", "RE_Status");
                    if (contact != null && contact.Rows.Count == 1)
                    {
                        if (TypeConvert.ToString(contact.Rows[0]["RE_Type"]) != "Member" ||
                            (TypeConvert.ToString(contact.Rows[0]["RE_Type"]) == "Member" && TypeConvert.ToString(contact.Rows[0]["RE_Status"]) == "Expired"))
                        {
                            //Populate Receipt #,Trans #, MemberCreatedBySelf
                            staffNewId = this.PrimaryDataRow["RE_Create_Staff_Id"];
                            //DS:02112012 - Set the Batch
                            batchId = this.PrimaryDataRow["RE_Batch_Id"];
                            recNum = this.PrimaryDataRow["RE_Membership_Reciept_No"];
                            memOrderId = this.PrimaryDataRow["RE_Membership_Order_Id"];

                            //Close RE_Member_Create in the background
                            this.FormView.CloseForm(true);
                            
                            TransitionPointParameter param = new TransitionPointParameter();
                            param.Construct();
                            param.SetUserDefinedParameter(5, "Sale_Member");
                            param.CopyToParameterList(param.ParameterList);

                            //Open RE_Member_Create form
                            Globals.ShowModalForm("RE_Member_Create", selectedDuplicateContactId, param.ParameterList);

                        }
                        else if (TypeConvert.ToString(contact.Rows[0]["RE_Type"]) == "Member" && (TypeConvert.ToString(contact.Rows[0]["RE_Status"]) == "Active" || TypeConvert.ToString(contact.Rows[0]["RE_Status"]) == "Pending"))
                        {
                            DialogResult dRes = Globals.PcmDialog("Member already exists. Click OK to view or Cancel to return.", "Information", MessageBoxButtons.OKCancel);
                            if (dRes == DialogResult.OK)
                            {
                                this.FormView.CloseForm(true);
                                //Open form by Notification Handler
                                Globals.ShowModalForm("Contact", selectedDuplicateContactId, null);
                            }
                            else
                            {
                                this.FormView.CloseForm(true);
                            }
                        }
                    }
                }
                else
                    Globals.ShowModalForm("Contact", selectedDuplicateContactId, null);
            }
        }

        /// <summary>
        /// Event handler for the OK click of the popup pwd challenge.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-08-08      DS              Initial version for Retail.                                                
        /// </history>
        private void Ok_Click(object sender, EventArgs e)
        {
            try
            {
                srcTxn2 = false;
                saveForm = false;
                if (changePassword)
                {
                    //If the authorized by and the pwd matches, then close and authorize the transaction.
                    //User selects OK but value not provided.
                    if (txtCurrentPassword.Text.Trim() == string.Empty || txtNewPassword.Text.Trim() == string.Empty || txtConfirmPassword.Text.Trim() == string.Empty)
                    {
                        this.txtCurrentPassword.Text = string.Empty;
                        this.txtNewPassword.Text = string.Empty;
                        this.txtConfirmPassword.Text = string.Empty;
                        this.txtCurrentPassword.Focus();
                        return;
                    }
                    string password = TypeConvert.ToString(Globals.ServerSqlIndex("RE_Staff", "Password_", staffId));

                    //Match the old password with the DB value. If matched go ahead, esle prompt the user.
                    if (String.Equals(Globals.Decrypt(password), txtCurrentPassword.Text))
                    {
                        //If new password and the confirm password does not match prompt the user with error.
                        if (!String.Equals(txtNewPassword.Text, txtConfirmPassword.Text))
                        {
                            PivotalMessageBox.Show("Password confirmation failed. Please enter again.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            this.txtNewPassword.Text = string.Empty;
                            this.txtConfirmPassword.Text = string.Empty;
                            this.txtNewPassword.Focus();
                            return;
                        }

                        //Now change the password for the Staff and set the field Prompt_To_Reset to false.
                        this.SystemClient.ExecuteServerTask("RE_Store", "SetStaffPassword", new Type[] { typeof(Id), typeof(string) },
                            new object[] { staffId, Globals.Encrypt(this.txtNewPassword.Text) });

                        //After successful validation and password change, close the pop-up.
                        popupChangePassword.Close();

                        authorizedBy = TypeConvert.ToDBValue(staffId);
                        if (this.PrimaryDataRow["RE_Membership_2_Order_Id"] != DBNull.Value)
                            srcTxn2 = true;
                        saveForm = true;
                    }
                    else
                    {
                        PivotalMessageBox.Show("Current Password verification failed. Please enter again.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.txtCurrentPassword.Text = string.Empty;
                        this.txtNewPassword.Text = string.Empty;
                        this.txtConfirmPassword.Text = string.Empty;
                        this.txtCurrentPassword.Focus();
                        return;
                    }
                }
                else
                {
                    //Verify the current password is correct and clock in the staff.
                    //User selects OK but value not provided.
                    if (txtCurrentPassword.Text.Trim() == string.Empty)
                    {
                        this.txtCurrentPassword.Text = string.Empty;
                        this.txtCurrentPassword.Focus();
                        return;
                    }

                    string password = TypeConvert.ToString(Globals.ServerSqlIndex("RE_Staff", "Password_", staffId));
                    //Match the password with the DB value. If matched go ahead, esle prompt the user.
                    if (String.Equals(Globals.Decrypt(password), txtCurrentPassword.Text))
                    {
                        //After successful validation and password change, close the pop-up.
                        popupAuthorization.Close();
                    }
                    else
                    {
                        PivotalMessageBox.Show("Password verification failed. Please enter again.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.txtCurrentPassword.Text = string.Empty;
                        this.txtCurrentPassword.Focus();
                        return;
                    }

                    authorizedBy = TypeConvert.ToDBValue(staffId);
                    if (this.PrimaryDataRow["RE_Membership_2_Order_Id"] != DBNull.Value)
                        srcTxn2 = true;
                    saveForm = true;
                }
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// Event handler for the Cancel click of the popup pwd challenge.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-08-08      DS              Initial version for Retail.                                                
        /// </history>
        private void Cancel_Click(object sender, EventArgs e)
        {
            saveForm = false;
        }
    }
}
